package com.api.gbhg.lbj.dao;

import com.api.gbhg.lbj.util.Budgetsources;
import com.google.common.base.Joiner;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;


import static com.api.gbhg.lbj.tool.Tools.getuf_gnkmId;
import static com.api.gbhg.lbj.tool.Tools.getuf_gxmdygnkmId;

/**
 * @author lbj
 * @version 1.0
 * @description: TODO 借款、还款
 * @date 2021/10/26 16:26
 */
public class LoanrepaymentDao {
    private static final Logger logger = LoggerFactory.getLogger("gbhg");
    private static final ReimbursementDao rei=new ReimbursementDao();
    /**
     * @description: TODO 主表金额扣减/退回（uf_jingfei）-借还款
     * @author
     * @date
     * @version 1.0
     */
    public boolean jhkMainJingfei(RecordSetTrans rst ,Map<String, String> param, Boolean flag) {
        boolean b = true;
        //流程记录id
        String lcjlid = param.get("lcjlid");
        //部门支出经济分类
        String bmzcjjfl = param.get("bmzcjjfl");

        BigDecimal sqbxje = new BigDecimal(param.get("money"));

        String querySql = "SELECT syed,dj FROM uf_jingfei  WHERE lcjlid=" + lcjlid + " AND bmzcjjfl=" + bmzcjjfl + " ";
        try {
            rst.executeQuery(querySql);
            while (rst.next()) {
                BigDecimal syed = new BigDecimal(rst.getDouble("syed"));
                if (flag) { //归档扣减
                    syed = syed.subtract(sqbxje);
                }else {//退回
                    syed = syed.add(sqbxje);
                }
                String updateSql = "update uf_jingfei set syed=" + syed.setScale(2, RoundingMode.HALF_UP).doubleValue() + " where lcjlid=" + lcjlid + " and bmzcjjfl=" + bmzcjjfl + "";
                logger.info("经费表-借款金额扣减：-------------------->" + updateSql);
                b = rst.executeUpdate(updateSql);
                //rst.commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //rst.rollback();
        }
        return b;
    }


    /**
     * @description: TODO 主表 jingfeilaiyuan 预算来源-扣减/退回&剩余额度-借还款
     * @author
     * @date
     * @version 1.0
     */
    public static Boolean jhksetyusuan(RecordSetTrans rst,Budgetsources bud, boolean flag) {

        RecordSet rs1 = rei.JinfeiQuery(bud);
        String lcjlid = bud.getYsxm();
        String money = bud.getSqbxje();
        String nd = bud.getNd();
        BigDecimal money1 = new BigDecimal(String.valueOf(money));
        boolean boo = true;
        try {
            while (rs1.next()) {
                BigDecimal syed = new BigDecimal(rs1.getString("syed"));//剩余额度
                String id = rs1.getString("id");

                if (flag) {
                    //归档扣减
                    syed = syed.subtract(money1);

                } else {
                    //退回
                    syed = syed.add(money1);

                }
                String update = "update uf_jingfeilaiyuan set syed=" + syed +" where lcid=" + lcjlid + " and id=" + id + " and nd=" + nd;
                logger.info("预算来源扣减sql:" + update +   "金额:" + money1);
                boo = rst.executeUpdate(update);
                //rst.commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //rst.rollback();
        }
        return boo;
    }


    /**
     * @description: TODO 归档前金额扣减（主表）
     * @author
     * @date
     * @version 1.0
     */
    public boolean jhkjingfeily(RecordSetTrans rst,Map<String, String> param, boolean flag) {
        boolean boo = true;
        String sqbxje = param.get("money");
        String lcjlid = param.get("lcjlid");
        Integer zcqd = Integer.valueOf(param.get("zcqd"));
        String fzysrfl = param.get("fzysrfl");
        String xzkmdm = param.get("xzkmdm");
        String nd = param.get("nd");
        Integer ysly = Integer.valueOf(param.get("ysly"));
        String zcdfczbkxm = param.get("zcdfczbkxm");
        String dw = param.get("dw");
        String jbbm = param.get("jbbm");
        Budgetsources bud = new Budgetsources();
        String gnkm = getuf_gnkmId(getuf_gxmdygnkmId(xzkmdm), nd);
        bud.setZcqd(zcqd);
        bud.setYsly(ysly);
        bud.setNd(nd);
        bud.setFzysrfl(fzysrfl);
        bud.setXzkmdm(xzkmdm);
        bud.setYsxm(lcjlid);
        bud.setGnkm(gnkm);
        bud.setSqbxje(sqbxje);
        bud.setZcdfczbkxm(zcdfczbkxm);
        bud.setDw(dw);
        bud.setJbbm(jbbm);
        logger.info("经办部门:"+jbbm+",预算来源lcjlid:" + lcjlid + ",支出渠道:" + zcqd + "预算来源:" + ysly + "非中央收入分类:" + fzysrfl + "选择科目代码:" + xzkmdm);
        //借还款金额
        BigDecimal money = new BigDecimal(sqbxje);

        try {
            boo = jhksetyusuan(rst,bud, flag);//冻结预算来源
            if (zcqd == 0) {//支出渠道-中央财政收入,收入类型-中央财政收入，中央科目级和下级的扣减
                boo = jhksetzyczzbkTest(rst,bud, money, flag);
            } else if (zcqd == 1 && fzysrfl.equals("8") || zcqd == 1 && fzysrfl.equals("5")) {//非中央财政收入-财政拨款
                boo = jhksetdfczbk(rst,bud, money, flag); //冻结地方财政拨款项目
            } else if (zcqd == 1) {
                boo = jhksetfzyczbk(rst,bud, money, flag);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return boo;
    }

    /**
     * @description: TODO 中央财政拨款收入——科目or下级 扣减
     * @author
     * @date
     * @version 1.0
     */
    public static boolean jhksetzyczzbkTest(RecordSetTrans rst,Budgetsources bud, BigDecimal money, boolean flag) {
        String uf_km = "uf_zyczbksr_km";
        String uf_xj = "uf_zyczbksr_xj";
        BaseBean baseBean = new BaseBean();
        int yj = Integer.parseInt(baseBean.getPropValue("Verification","yj"));//科目级
        int xj = Integer.parseInt(baseBean.getPropValue("Verification","xj"));//下级
        logger.info("科目级yj:"+yj+",下级xj:"+xj);
        int sum1 = 0;
        int sum2 = 0;
        boolean boo = true;
        RecordSet rs = rei.zyJinfeiQuery(bud);
        while (rs.next()) {
            String zyczbksr = rs.getString("hpssjid");//中央财政拨款收入_核批时数据id
            String kmjxj = rs.getString("kmjxj");//0:科目级，1:下级
            logger.info("中央财政拨款收入_核批时数据id:"+zyczbksr+"科目级/下级:"+kmjxj);
            if (StringUtils.isNotBlank(zyczbksr)) {
                String[] sta = zyczbksr.split("_");//当年结转核批下划线分割
                sum1 = Integer.parseInt(sta[0]);//9为科目级，10为科目下级
                sum2 = Integer.parseInt(sta[1]);//表id
                if (sum1 == yj) {
                    boo = jhksetzyczzbk(rst,bud, money, uf_km, sum2,kmjxj,flag);//只扣科目级
                } else if (sum1 == xj) {
                    Boolean boo1=true;
                    List<String> superiorId = rei.getSuperiorId(sum2);
                    String joinId = Joiner.on(",").join((Iterable<?>) superiorId);
                    for (int i = 0 ; i<joinId.split(",").length;i++){
                        String id = joinId.split(",")[i];
                        boo1 = jhksetzyczzbk(rst,bud, money, uf_xj, Integer.valueOf(id),kmjxj, flag);//扣减所有科目下级
                        logger.info("所有下级id"+id);
                    }
                    RecordSet zyczxj = rei.getZyczxj(sum2);
                    zyczxj.next();
                    Integer szgnkm = zyczxj.getInt("szgnkm");
                    boolean boo2 = jhksetzyczzbk(rst,bud, money, uf_km, szgnkm, kmjxj,flag);//扣减科目级
                    if (!boo1 || !boo2) {
                        return false;
                    }
                }
            }
        }
        return boo;
    }

    /**
     * @description: TODO 中央财政拨款收入——科目 扣减 (借还款)
     * @author
     * @date
     * @version 1.0
     */
    public static boolean jhksetzyczzbk(RecordSetTrans rst,Budgetsources bud, BigDecimal money,String tableName,Integer id,String kmjxj, boolean flag) {
        //uf_zyczbksr_km
        Integer ysly = bud.getYsly();
        String sql="";
        if (kmjxj.equals("0")){//0:科目级,1:下级
            sql = "select djje,sjbxje,snjzhpbxje,snjzhpsyje,hpsyje,snjzhpdjje from "+tableName+" where id ="+id;
        }else {
            sql = "select djje,sjbxje,snjzhpbxje,snjzhpsyje,yhpsy,snjzhpdjje from "+tableName+" where id ="+id;
        }
        logger.info("中央财政拨款收入——科目查询sql:"+sql);
        boolean boo = true;
        try {
            rst.executeQuery(sql);
            while (rst.next()) {
                String sjbxje1 = rst.getString("sjbxje");
                if (StringUtils.isBlank(sjbxje1)) {
                    sjbxje1 = "0.00";
                }
                String je="";
                if (kmjxj.equals("0")){
                    je=rst.getString("hpsyje");
                }else {
                    je=rst.getString("yhpsy");
                }
                if (StringUtils.isBlank(je)) {
                    je = "0.00";
                }
                String snjzhpbxje1 = rst.getString("snjzhpbxje");
                if (StringUtils.isBlank(snjzhpbxje1)) {
                    snjzhpbxje1 = "0.00";
                }
                String snjzhpsyje1 = rst.getString("snjzhpsyje");
                if (StringUtils.isBlank(snjzhpsyje1)) {
                    snjzhpsyje1 = "0.00";
                }
                BigDecimal sjbxje = new BigDecimal(sjbxje1);//实际报销金额
                BigDecimal hpsyje = new BigDecimal(je);//核批剩余金额
                BigDecimal snjzhpbxje = new BigDecimal(snjzhpbxje1);//上年结转核批报销金额
                BigDecimal snjzhpsyje = new BigDecimal(snjzhpsyje1);//上年结转核批剩余金额
                String updateSql = "";
                if (ysly == 0) {//0:当年
                    if (hpsyje.compareTo(BigDecimal.ZERO) == -1 || hpsyje.compareTo(BigDecimal.ZERO) == 0) {
                        logger.info("金额不足");
                        boo = false;
                        return boo;
                    }
                    if (flag) {//true:归档借款
                        hpsyje = hpsyje.subtract(money);
                        sjbxje = sjbxje.add(money);
                    } else {//归档还款
                        hpsyje = hpsyje.add(money);
                        sjbxje = sjbxje.subtract(money);
                    }
                    if (kmjxj.equals("0")){
                        updateSql = "update "+tableName+" set hpsyje=" + hpsyje +  ",sjbxje=" + sjbxje + " where id="+id;
                    }else {
                        updateSql = "update "+tableName+" set yhpsy=" + hpsyje +  ",sjbxje=" + sjbxje + " where id="+id;
                    }
                } else if (ysly == 1) {//上年
                    if (snjzhpsyje.compareTo(BigDecimal.ZERO) == -1 || snjzhpsyje.compareTo(BigDecimal.ZERO) == 0) {
                        logger.info("金额不足");
                        boo = false;
                        return boo;
                    }
                    if (flag) {//true:归档借款
                        snjzhpsyje = snjzhpsyje.add(money);
                        snjzhpbxje = snjzhpbxje.subtract(money);
                    } else {//归档还款
                        snjzhpsyje = snjzhpsyje.subtract(money);
                        snjzhpbxje = snjzhpbxje.add(money);

                    }
                    updateSql = "update "+tableName+" set snjzhpsyje=" + snjzhpsyje   + ",snjzhpbxje=" + snjzhpbxje + " where id="+id;
                }
                logger.info("核批剩余金额：" + hpsyje +  "实际报销金额:" + sjbxje + "上年结转核批剩余金额：" + snjzhpsyje + "上年结转核批报销金额:" + snjzhpbxje);
                logger.info("中央财政拨款收入扣减sql：" + updateSql);
                boo = rst.executeUpdate(updateSql);
                //rst.commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //rst.rollback();
        }
        return boo;
    }

    /**
     * @description: TODO 修改 地方财政拨款项目冻结&剩余额度
     * @author
     * @date
     * @version 1.0
     */
    public static boolean jhksetdfczbk(RecordSetTrans rst ,Budgetsources bud, BigDecimal money, boolean flag) {

        String zcdfczbkxm = bud.getZcdfczbkxm();
        Integer ysly = bud.getYsly();
        String dw = bud.getDw();
        String sql = "select sjsrsy,djje,snjzhpbxje,snjzhpsyje,snjzhpdjje,sjbxje from uf_fzysrxm where id=" + zcdfczbkxm + " and szdw=" + dw;
        boolean boo = true;
        try {
            rst.executeQuery(sql);
            while (rst.next()) {
                String sjbxje1 = rst.getString("sjbxje");
                if (StringUtils.isBlank(sjbxje1)) {
                    sjbxje1 = "0.00";
                }
                String sjsrsy1 = rst.getString("sjsrsy");
                if (StringUtils.isBlank(sjsrsy1)) {
                    sjsrsy1 = "0.00";
                }
                String snjzhpbxje1 = rst.getString("snjzhpbxje");
                if (StringUtils.isBlank(snjzhpbxje1)) {
                    snjzhpbxje1 = "0.00";
                }
                String snjzhpsyje1 = rst.getString("snjzhpsyje");
                if (StringUtils.isBlank(snjzhpsyje1)) {
                    snjzhpsyje1 = "0.00";
                }
                BigDecimal sjsrsy = new BigDecimal(sjsrsy1);//实际收入剩余
                BigDecimal sjbxje = new BigDecimal(sjbxje1);//实际报销金额
                BigDecimal snjzhpsyje = new BigDecimal(snjzhpsyje1);//上年结转核批剩余金额
                BigDecimal snjzhpbxje = new BigDecimal(snjzhpbxje1);//上年结转核批报销金额
                String update = "";
                if (ysly == 0) {
                    if (sjsrsy.compareTo(BigDecimal.ZERO) == 0 || sjsrsy.compareTo(BigDecimal.ZERO) == -1) {
                        logger.info("实际收入剩余金额不足");
                        boo = false;
                        return boo;
                    }
                    if (flag) {//归档借款
                        sjsrsy = sjsrsy.subtract(money);
                        sjbxje = sjbxje.add(money);
                    } else {//归档还款
                        sjsrsy = sjsrsy.add(money);
                        sjbxje = sjbxje.subtract(money);
                    }
                    update = "update uf_fzysrxm set sjsrsy=" + sjsrsy +  ",sjbxje=" + sjbxje + " where id=" + zcdfczbkxm + " and szdw=" + dw;
                } else if (ysly == 1) {
                    if (snjzhpsyje.compareTo(BigDecimal.ZERO) == 0 || snjzhpsyje.compareTo(BigDecimal.ZERO) == -1) {
                        logger.info("以前年度结转实际金额不足");
                        boo = false;
                        return boo;
                    }
                    if (flag) {//归档借款
                        snjzhpsyje = snjzhpsyje.subtract(money);
                        snjzhpbxje = snjzhpbxje.add(money);
                    } else {//归档还款
                        snjzhpsyje = snjzhpsyje.add(money);
                        snjzhpbxje = snjzhpbxje.subtract(money);

                    }
                    update = "update uf_fzysrxm set snjzhpsyje=" + snjzhpsyje + ",snjzhpbxje" + snjzhpbxje +  " where id=" + zcdfczbkxm + " and szdw=" + dw;
                }
                logger.info("上年结转核批剩余金额：" + snjzhpsyje + "上年结转核批报销金额:" + snjzhpbxje + "实际收入剩余:" + sjsrsy);
                logger.info("明细表地方财政拨款项目sql:" + update);
                boo = rst.executeUpdate(update);
                //rst.commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //rst.rollback();
        }
        return boo;
    }

    /**
     * @description: TODO 修改 非财政拨款项目冻结&剩余额度
     * @author
     * @date
     * @version 1.0
     */
    public static boolean jhksetfzyczbk(RecordSetTrans rst,Budgetsources bud, BigDecimal money, boolean flag) {

        String fzysrfl = bud.getFzysrfl();
        Integer ysly = bud.getYsly();
        String nd = bud.getNd();
        String dw = bud.getDw();

        String sql = "select djje,snjzhpbxje,snjzhpsyje,snjzhpdjje,sjbxje,sjsrsy from uf_fzysr where szfl=" + fzysrfl + " and=" + nd + " and dw=" + dw;
        logger.info("非中央sql--:" + sql);
        boolean boo = true;
        try {
            rst.executeQuery(sql);
            while (rst.next()) {
                String sjbxje1 = rst.getString("sjbxje");
                if (StringUtils.isBlank(sjbxje1)) {
                    sjbxje1 = "0.00";
                }
                String sjsrsy1 = rst.getString("sjsrsy");
                if (StringUtils.isBlank(sjsrsy1)) {
                    sjsrsy1 = "0.00";
                }

                String snjzhpbxje1 = rst.getString("snjzhpbxje");
                if (StringUtils.isBlank(snjzhpbxje1)) {
                    snjzhpbxje1 = "0.00";
                }
                String snjzhpsyje1 = rst.getString("snjzhpsyje");
                if (StringUtils.isBlank(snjzhpsyje1)) {
                    snjzhpsyje1 = "0.00";
                }
                BigDecimal sjsrsy = new BigDecimal(sjsrsy1);//实际收入

                BigDecimal sjbxje = new BigDecimal(sjbxje1);//实际报销金额
                BigDecimal snjzhpsyje = new BigDecimal(snjzhpsyje1);//上年结转核批剩余金额
                BigDecimal snjzhpbxje = new BigDecimal(snjzhpbxje1);//上年结转核批报销金额
                String update = "";
                if (ysly == 0) {
                    if (sjsrsy.compareTo(BigDecimal.ZERO) == -1 || sjsrsy.compareTo(BigDecimal.ZERO) == 0) {
                        logger.info("实际收入金额不足");
                        boo = false;
                        return boo;
                    }
                    if (flag) {//归档借款
                        sjsrsy = sjsrsy.subtract(money);
                        sjbxje = sjbxje.add(money);
                    } else {//归档还款
                        sjsrsy = sjsrsy.add(money);
                        sjbxje = sjbxje.subtract(money);
                    }
                    update = "update uf_fzysr set sjsrsy=" + sjsrsy +  ",sjbxje=" + sjbxje + " where szfl=" + fzysrfl + " and dw=" + dw;
                } else if (ysly == 1) {
                    if (snjzhpsyje.compareTo(BigDecimal.ZERO) == -1 || snjzhpsyje.compareTo(BigDecimal.ZERO) == 0) {
                        logger.info("以前年度实际结转实际收入金额不足");
                        boo = false;
                        return boo;
                    }
                    if (flag) {//归档借款
                        snjzhpbxje = snjzhpbxje.add(money);
                        snjzhpsyje = snjzhpsyje.subtract(money);
                    } else {//归档还款
                        snjzhpbxje = snjzhpbxje.subtract(money);
                        snjzhpsyje = snjzhpsyje.add(money);
                    }
                    update = "update uf_fzysr set snjzhpsyje=" + snjzhpsyje +  ",snjzhpbxje=" + snjzhpbxje + " where szfl=" + fzysrfl  + " and dw=" + dw;
                }
                logger.info( "实际报销金额:" + sjbxje + "实际收入剩余:" + sjsrsy + "上年结转核批报销金额:" + snjzhpbxje + "上年结转核批剩余金额:" + snjzhpsyje);
                logger.info("非财政拨款项目-借还款-sql:" + update);
                boo = rst.executeUpdate(update);
                //rst.commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //rst.rollback();
        }
        return boo;
    }
}
